#!/bin/bash
# 待改进版本，暂时存储

# 设置环境变量
USER_NAME='root'
USER_HOME="/${USER_NAME}/.ssh"
SSH_CONFIG_FILE='/etc/ssh/ssh_config'
USER_PASSWD='123456'
HOSTADDR_PRE='10.0.0'
HOST_LIST="${HOSTADDR_PRE}.12 ${HOSTADDR_PRE}.13 ${HOSTADDR_PRE}.16"
HOSTNAME_LIST='ubuntu24-13 rocky9-12 ubuntu24-16'
HOSTS_FILE='/etc/hosts'
# 准备基本环境
base_env() {
  yum install expect -y
  [ -d ${USER_HOME} ] && rm -rf ${USER_HOME}
  ssh-keygen -t rsa -P "" -f ${USER_HOME}/id_rsa
  sed -i '/ask/{s/#/ /; s/ask/no/}' ${SSH_CONFIG_FILE}
}
# expect自动化交互过程
expect_auto() {
  remote_host=$1
  expect -c "
    spawn ssh-copy-id -i ${USER_HOME}/id_rsa.pub $1
    expect {
      \"*yes/no*\" {send \"yes\r\"; exp_continue}
      \"*password*\" {send \"$USER_PASSWD\r\"; exp_continue}
      \"*Password*\" {send \"$USER_PASSWD\r\";}
    } "
}
# 跨主机免认证环境
auth_auto() {
  for i in ${HOST_LIST} ${HOSTNAME_LIST}
  do
    expect_auto ${USER_NAME}@$i
    scp -rp ${HOSTS_FILE} ${USER_NAME}@$i:${HOSTS_FILE}
  done
}
# 设定主机名
hostname_set() {
  for i in ${HOSTNAME_LIST}
  do
    ssh ${USER_NAME}@$i "hostnamectl set-hostname $i"
  done
}

# 主函数执行
main() {
  # 基本环境准备
  base_env
  # 跨主机免密认证
  auth_auto
  # 设定主机名
  hostname_set
}
# 执行主函数
main

